import { defineStore } from 'pinia';

// 用户状态管理
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    isLoggedIn: false,
    token: null,
    fansSince: null, // 成为粉丝的时长
    isVip: false,    // 是否是VIP用户
    vipExpiryDate: null // VIP过期时间
  }),
  
  getters: {
    getUserInfo: (state) => state.userInfo,
    getToken: (state) => state.token,
    getIsLoggedIn: (state) => state.isLoggedIn,
    getFansSince: (state) => state.fansSince,
    getIsVip: (state) => state.isVip,
    getVipExpiryDate: (state) => state.vipExpiryDate
  },
  
  actions: {
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      this.isLoggedIn = true;
      // 计算成为粉丝的时长（随机生成一些年数）
      const years = Math.floor(Math.random() * 10) + 1;
      const now = new Date();
      const fansSince = new Date(now.getFullYear() - years, now.getMonth(), now.getDate());
      this.fansSince = fansSince;
    },
    
    setToken(token) {
      this.token = token;
      localStorage.setItem('token', token);
    },
    
    setVipStatus(isVip, expiryDate = null) {
      this.isVip = isVip;
      this.vipExpiryDate = expiryDate;
    },
    
    logout() {
      this.userInfo = null;
      this.isLoggedIn = false;
      this.token = null;
      this.isVip = false;
      this.vipExpiryDate = null;
      localStorage.removeItem('token');
    },
    
    // 初始化用户状态
    initUserState() {
      const token = localStorage.getItem('token');
      if (token) {
        this.token = token;
        // 这里应该从服务器验证token并获取用户信息
        // 但在模拟环境中，我们直接设置用户信息
        this.isLoggedIn = true;
        this.userInfo = {
          username: 'xuezhiqianfan',
          avatar: 'https://picsum.photos/64/64?random=1',
          nickname: '薛之谦的小迷弟/妹'
        };
      }
    }
  }
});

// 应用状态管理
export const useAppStore = defineStore('app', {
  state: () => ({
    loading: false,
    error: null,
    currentTab: 'concerts', // 默认选中演唱会标签
    filter: {
      keyword: '',
      type: 'all'
    },
    pagination: {
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  }),
  
  getters: {
    getLoading: (state) => state.loading,
    getError: (state) => state.error,
    getCurrentTab: (state) => state.currentTab,
    getFilter: (state) => state.filter,
    getPagination: (state) => state.pagination
  },
  
  actions: {
    setLoading(loading) {
      this.loading = loading;
    },
    
    setError(error) {
      this.error = error;
    },
    
    clearError() {
      this.error = null;
    },
    
    setCurrentTab(tab) {
      this.currentTab = tab;
    },
    
    setFilter(filter) {
      this.filter = { ...this.filter, ...filter };
    },
    
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
    }
  }
});